<template>
  <view class="echarts-inner">
    <view class="inner-header">
      <view class="all-num">
        <view>{{allData}}</view>
        <view>{{state.tabActiveItem.content}}</view>
      </view>
      <view class="echarts-tab">
        <view class="tab-inner">
          <view
            :class="[
              'item-tab',
              {
                'tab-active': state.tabActive === item.value,
                'item-tab-active-0': state.tabActive === 0,
                'item-tab-active-1': state.tabActive === 1,
                'item-tab-active-2': state.tabActive === 2
              },
            ]"
            v-for="(item, index) in state.tabLists"
            :key="index"
            @tap="handleTab(item)"
          >
            {{ item.label }}
          </view>
        </view>
      </view>
    </view>
    <view class="l-echart">
      <!-- :customStyle="state.customStyle" -->
      <l-echart ref="chartRef"></l-echart>
    </view>
  </view>
</template>

<script setup>
import LEchart from '../uni_modules/lime-echart/components/l-echart/l-echart.vue';
const echarts = require('../uni_modules/lime-echart/static/echarts.min.js')
import {
  onLaunch,
  onShow,
  onHide,
  onUnload,
} from "@dcloudio/uni-app";
import { ref, reactive, watch, onMounted, defineEmits, toRefs } from "vue";
import * as API from "../../api/api";
import { getTime, handleCommonSpeed } from "../../utils/util";
import { storeToRefs } from "pinia";
import { useRunInfoStore } from "../../store/runInfo";
import { useAppStore } from "../../store/app";
import { useShareStore } from "../../store/share";
const useShareData = useShareStore();
const useAppData = useAppStore();
const useRunInfoData = useRunInfoStore();
const props = defineProps({
  xAxisData: {
    type: Array,
    default: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
  },
  seriesData: {
    type: Array,
    default: []
  },
  allData: {
    type: String,
    default: "0"
  },
  dateType: "day",
  isReflesh: {
    type: Boolean,
    default: false
  }
})
const state = reactive({
  customStyle: {
    width: "1500px"
  },
	userInfo: null,
	tabActiveItem: {
		label: "里程",
		value: 0,
		content: "累计里程（公里）",
    key: "distanceDatas"
	},
  tabActive: 0,
  tabLists: [
    {
      label: "里程",
      value: 0,
      content: "累计里程（公里）",
      key: "distanceDatas"
    },
    {
      label: "时长",
      value: 1,
      content: "累计时长（小时）",
      key: "durationDatas"
    },
    {
      label: "配速",
      value: 2,
      content: "最佳平均配速",
      key: "paceDatas"
    },
  ],
  xAxisData: [],
  seriesData: [],
  showNoTitle: false
});
const {xAxisData, seriesData, allData, dateType, isReflesh} = toRefs(props)
const emit = defineEmits(["onEchartsTab"])


const chartRef = ref(null)
const option = {
	// tooltip: {
	// 	trigger: 'axis',
	// 	axisPointer: {
	// 		type: 'shadow' 
	// 	},
	// 	confine: true
	// },
	// legend: {
	// 	data: ['热度', '正面', '负面']
	// },
  title: {
    show: state.showNoTitle,
    text: "暂无数据",
    x: "center",
    y: "center",
    textStyle: {
      color: "#ccc",
      fontWeight: "normal",
      fill: "#9d9d9d",
      fontWeight: "bold",
      text: "暂无数据",
      fontFamily: "Microsoft YaHei",
      fontSize: "20px",
    },
  },
	grid: {
		left: 0,
		right: 20,
		bottom: 10,
		top: 30,
		containLabel: true
	},
 xAxis: {
    type: 'category',
    axisTick: {
      show: false
    },
    axisLine: {
      show: false
    },
    axisLabel: {
      interval: 0  // 坐标轴刻度标签的显示间隔,x轴值全部展示，不隐藏
    },
    data: props.xAxisData
  },
  yAxis: {
    type: 'value',
    axisLabel: {
      show: false
    }
  },
  dataZoom: [
    {
      type: 'inside', // 支持内部鼠标滚动平移
      // start: 0,
      // end: 10,
      xAxisIndex: 0,
      // zoomOnMouseWheel: false, // 关闭滚轮缩放
      // moveOnMouseWheel: true, // 开启滚轮平移
      // moveOnMouseMove: false, // 鼠标移动能触发数据窗口平移
      startValue: props.xAxisData.length - 7, // 从末尾开始 从头开始 0 。
      endValue: props.xAxisData.length - 1  // 一次性展示6个。
    },
    // {
    //   // 设置滚动条的隐藏与显示
    //   show: dateType.value === "month" ? true : false,
    //   // 设置滚动条类型
    //   type: "slider",
    //   // 设置背景颜色
    //   backgroundColor: "#fff",
    //   // 设置选中范围的填充颜色
    //   fillerColor: "#71F8B7",
    //   // 设置边框颜色
    //   borderColor: "#71F8B7",
    //   // 是否显示detail，即拖拽时候显示详细数值信息
    //   showDetail: false,
    //   // 数据窗口范围的起始数值
    //   startValue: 0,
    //   // 数据窗口范围的结束数值（一页显示多少条数据）
    //   endValue: 6,
    //   // empty：当前数据窗口外的数据，被设置为空。
    //   // 即不会影响其他轴的数据范围
    //   filterMode: "empty",
    //   // 设置滚动条宽度，相对于盒子宽度
    //   width: "100%",
    //   // 设置滚动条高度
    //   height: 8,
    //   // 设置滚动条显示位置
    //   left: "center",
    //   // 是否锁定选择区域（或叫做数据窗口）的大小
    //   zoomLock: true,
    //   // 控制手柄的尺寸
    //   handleSize: 0,
    //   // dataZoom-slider组件离容器下侧的距离
    //   bottom: 0,
    //   showDataShadow: false, //关闭滚动条背景数据走向 ***
    //   brushSelect: false, // 关闭滚动条缩放 
    // }
  ],
  series: [
    {
      data: props.seriesData,
      type: 'bar',
      barWidth: 22,
      itemStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: '#71F8B7' },
          { offset: 1, color: '#D2FECF' }
        ])
      },
      label:{
        show:true,
        position:'top',
        // width: 45,
        // overflow: "truncate",
        // ellipsis: "...",
        formatter:function(data){
          if (Number(data.value[1]) > 0) {
            if (state.tabActiveItem.key === "paceDatas") {
              let paceObj = handleCommonSpeed(data.value[1])
              console.log("paceObj====", paceObj)
              if (paceObj.sen > 0) {
                return paceObj.pace
              } else {
                return ""
              }
            } else if (state.tabActiveItem.key === "durationDatas") {
              return data.value[1]
            } else {
              return data.value[1]
            }
          } else {
            return ""
          }
        }
      }
    }
  ]
};

const handleSetOption = () => {
	setTimeout(async()=>{
		if(!chartRef.value) return
		const myChart = await chartRef.value.init(echarts)
		myChart.setOption(option, true)
	},300)
}


onMounted( ()=>{
	handleSetOption()
})


const handleTab = (item) => {
	state.tabActive = item.value;
	state.tabActiveItem = item;
  emit("onEchartsTab", state.tabActiveItem)
};

onShow(() => {
  state.userInfo = uni.getStorageSync("userInfo")
    ? JSON.parse(uni.getStorageSync("userInfo"))
    : null;
});

watch(() => isReflesh.value, (newVal, oldVal) => {
  if (newVal) {
    state.tabActive = 0;
    state.tabActiveItem = {
      label: "里程",
      value: 0,
      content: "累计里程（公里）",
      key: "distanceDatas"
    };
    emit("onEchartsTab", state.tabActiveItem)
  }
}, {immediate: true, deep: true})

watch(() => seriesData.value, (newVal, oldVal) => {
  state.showNoTitle = newVal.every(item => {
    return Number(item[1]) === 0
  })
  option.title.show = state.showNoTitle
  handleSetOption()
}, {immediate: true, deep: true})
</script>

<style lang="scss" scoped>
.echarts-inner {
  .inner-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    .all-num {
      font-family: PingFangTC, PingFangTC;
      font-weight: 400;
      font-size: 24rpx;
      color: rgba(34, 34, 34, 0.86);
      view:first-child {
        width: 200rpx;
        font-weight: 900;
        font-size: 44rpx;
        margin-bottom: 8rpx;
        overflow: hidden; /* 确保超出容器的文本被裁剪 */
        white-space: nowrap; /* 确保文本在一行内显示 */
        text-overflow: ellipsis; /* 使用省略号表示文本超出 */
      }
    }
    .echarts-tab {
      width: 280rpx;
      height: 64rpx;
      border-radius: 16rpx;
      background: linear-gradient(162deg, rgba(115, 248, 183, 1), rgba(189, 235, 252, 1));
      font-size: 24rpx;
      padding: 2rpx;
      .tab-inner {
        background: #fff;
        border-radius: 16rpx;
        display: flex;
        justify-content: space-between;
        align-items: center;
      }
      .item-tab {
        width: 92rpx;
        height: 64rpx;
        text-align: center;
        line-height: 64rpx;
        border-radius: 16rpx;
        position: relative;
        &:nth-child(2) {
          &::before {
            content: "";
            width: 2rpx;
            height: 28rpx;
            border-left: 2rpx solid #d8e8ee;
            position: absolute;
            top: 50%;
            left: 0;
            transform: translateY(-50%);
          }
          &::after {
            content: "";
            width: 2rpx;
            height: 28rpx;
            border-left: 2rpx solid #d8e8ee;
            position: absolute;
            top: 50%;
            right: 0;
            transform: translateY(-50%);
          }
        }
      }
      .item-tab-active-0 {
        &:nth-child(2) {
          &::before {
            display: none;
          }
        }
      }
      .item-tab-active-1 {
        &:nth-child(2) {
          &::before {
            display: none;
          }
          &::after {
            display: none;
          }
        }
      }
      .item-tab-active-2 {
        &:nth-child(2) {
          &::after {
            display: none;
          }
        }
      }
      .tab-active {
        background: linear-gradient(151deg, #f7fff1 0%, #e8fbff 100%);
        box-shadow: 0rpx 2rpx 8rpx 0rpx rgba(187, 203, 203, 0.7);
        border-radius: 16rpx;
        font-weight: 600;
      }
    }
  }
  .l-echart{
    width: 592rpx;
    height: 390rpx;
    overflow: auto;
  }
}
</style>
